

import React, { useRef, useEffect, useState } from "react";
import style from "./Home.module.css";
import { useNavigate } from "react-router-dom";

function getTodayStr() {
  const weekMap = ['日','一','二','三','四','五','六'];
  const d = new Date();
  return `${d.getFullYear()}年${d.getMonth()+1}月${d.getDate()}日，周${weekMap[d.getDay()]}`;
}

function CalendarPotIcon() {
  // 彩色小锅SVG
  return (
    <svg className={style.iconCalSvg} width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
      <ellipse cx="14" cy="20" rx="10" ry="5" fill="#7c6a5a"/>
      <ellipse cx="14" cy="18" rx="10" ry="5" fill="#b6a48a"/>
      <ellipse cx="14" cy="17" rx="8" ry="4" fill="#fff"/>
      <circle cx="10.5" cy="16.5" r="1.5" fill="#ff9800"/>
      <circle cx="14" cy="17.5" r="1.5" fill="#ff9800"/>
      <circle cx="17.5" cy="15.5" r="1.2" fill="#ff9800"/>
      <ellipse cx="14" cy="13" rx="7" ry="2.5" fill="#b6a48a"/>
      <ellipse cx="14" cy="12.5" rx="6" ry="2" fill="#fff"/>
      <ellipse cx="14" cy="11.5" rx="4.5" ry="1.2" fill="#ff9800"/>
    </svg>
  );
}

function BellIcon() {
  // 白色铃铛+棕色圆环
  return (
    <svg className={style.bellSvg} width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="24" cy="24" r="22" stroke="#a97c50" strokeWidth="1.5" fill="none" />
      <path d="M24 38c2.2 0 4-1.8 4-4h-8c0 2.2 1.8 4 4 4zm10-8V22c0-5.1-3.1-9.3-8-10.2V10a2 2 0 1 0-4 0v1.8C17.1 12.7 14 16.9 14 22v8l-2 2v2h28v-2l-2-2z" fill="#fff"/>
    </svg>
  );
}

function CircleProgress({ percent, size = 90, stroke = 7, color = '#fff' }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const offset = c * (1 - percent / 100);
  return (
    <svg width={size} height={size} className={style.circleSvg}>
      <circle cx={size/2} cy={size/2} r={r} stroke="#fff4" strokeWidth={stroke} fill="none" />
      <circle cx={size/2} cy={size/2} r={r} stroke={color} strokeWidth={stroke} fill="none" strokeDasharray={c} strokeDashoffset={offset} strokeLinecap="round" />
    </svg>
  );
}

function BarChart({ values }) {
  // values: [2,4,7,10,8,5,3]
  const max = Math.max(...values);
  return (
    <svg width="70" height="40" className={style.barSvg}>
      {values.map((v, i) => (
        <rect key={i} x={i*10+2} y={40-v/max*32} width="6" height={v/max*32} rx="2" fill="#fff" opacity="0.9" />
      ))}
      {/* 小圆点 */}
      {values.map((v, i) => (
        <circle key={i} cx={i*10+5} cy={38} r="2" fill="#fff" opacity="0.7" />
      ))}
    </svg>
  );
}

function ECGIcon() {
  // 红色心电图SVG
  return (
    <svg width="48" height="18" viewBox="0 0 48 18" fill="none" xmlns="http://www.w3.org/2000/svg" style={{display:'block',margin:'8px auto 0 auto'}}>
      <polyline points="0,9 8,9 12,15 18,3 24,15 28,9 34,9 38,5 42,13 48,9" stroke="#ff3b3b" strokeWidth="2.5" fill="none" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
}

function ECGIconInline() {
  // 横向心电图，适合放在圆环左侧
  return (
    <svg width="32" height="32" viewBox="0 0 32 32" fill="none" style={{display:'block'}} xmlns="http://www.w3.org/2000/svg">
      <polyline points="0,16 5,16 8,28 13,6 18,28 22,16 32,16" stroke="#ff3b3b" strokeWidth="2.5" fill="none" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
}

// GradientHeart 组件
function GradientHeart({ breath = 1 }) {
  // 渐变红色心脏SVG，带呼吸动画
  return (
    <svg width="28" height="28" viewBox="0 0 28 28" fill="none" style={{transform:`scale(${breath})`, transition:'transform 0.12s linear'}} xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="heartGradient" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#ff5f6d"/>
          <stop offset="100%" stopColor="#ff3b3b"/>
        </linearGradient>
      </defs>
      <path d="M14 25s-8.5-6.2-8.5-12.1C5.5 8.1 8.4 5.5 11.5 5.5c1.7 0 3.2 1 4.1 2.5C16.3 6.5 17.8 5.5 19.5 5.5c3.1 0 6 2.6 6 7.4C22.5 18.8 14 25 14 25z" fill="url(#heartGradient)"/>
    </svg>
  );
}

function AnimatedECG({ amplitude = 1, speed = 0.01 }) {
  // 高频锯齿心电图动画，呼吸幅度同步
  const [points, setPoints] = useState([]);
  const phaseRef = useRef(0);
  // 更低频率的锯齿波形模板
  const template = [16,16,16,3,16,16,16,16,16,3,16,16,16,16,16,3,16,16,16];
  const baseline = 12;
  useEffect(() => {
    let running = true;
    function animate() {
      phaseRef.current += speed; // 频率可控
      const pts = [];
      for (let i = 0; i <= 16; i++) {
        const x = i * 2;
        const idx = (i + phaseRef.current) % template.length;
        const idx0 = Math.floor(idx);
        const idx1 = (idx0 + 1) % template.length;
        const t = idx - idx0;
        const y0 = template[idx0] * (1 - t) + template[idx1] * t;
        const y = (y0 - baseline) * amplitude + baseline;
        pts.push(`${x},${y}`);
      }
      setPoints(pts);
      if (running) requestAnimationFrame(animate);
    }
    animate();
    return () => { running = false; };
  }, [amplitude, speed]);
  return (
    <svg width="32" height="18" viewBox="0 0 32 18" fill="none" xmlns="http://www.w3.org/2000/svg">
      <polyline points={points.join(' ')} stroke="#ff3b3b" strokeWidth="2.5" fill="none" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
}

const metrics = [
  {
    color: style.metricGreen,
    icon: '💚',
    title: '弗洛伊德评分',
    type: 'circle',
    value: 80,
    label: '健康',
    percent: 80,
  },  
  {
    color: style.metricOrange,
    icon: '😞',
    title: '情绪',
    type: 'bar',
    value: '伤心',
    bar: [2,4,7,10,8,5,3],
  },
  {
    color: style.metricBlue,
    icon: '👣',
    title: '步数',
    type: 'number',
    value: 1806,
    label: '步',
  },
  {
    color: style.metricRed,
    icon: '🔥',
    title: '热量',
    type: 'number',
    value: 95,
    label: '千卡',
  },
  {
    color: style.metricPurple,
    icon: '🧗‍♂️',
    title: '海拔',
    type: 'number',
    value: 123,
    label: '米',
  },
  {
    color: style.metricYellow,
    icon: '😤',
    title: '压力',
    type: 'circle',
    value: 30,
    label: '抗压力强',
    percent: 60,
  },
];

// 左滑医生卡片组件
function SwipeDoctorCard({ avatar, name, tag, meta, score, users, checked, onPhoneClick, onChatClick }) {
  const [offset, setOffset] = React.useState(0);
  const startX = React.useRef(0);
  const dragging = React.useRef(false);
  // 触摸事件
  const onTouchStart = e => {
    dragging.current = true;
    startX.current = e.touches[0].clientX;
  };
  const onTouchMove = e => {
    if (!dragging.current) return;
    const dx = e.touches[0].clientX - startX.current;
    setOffset(Math.max(Math.min(dx, 0), -60));
  };
  const onTouchEnd = () => {
    dragging.current = false;
    setOffset(offset < -30 ? -60 : 0);
  };
  return (
    <div style={{position:'relative',overflow:'hidden',marginBottom: '16px'}}>
      {/* 按钮区：电话+聊天 */}
      <div style={{
        position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%)',
        zIndex: 1, transition: 'right 0.2s, opacity 0.2s', pointerEvents: offset === -60 ? 'auto' : 'none',
        opacity: offset === -60 ? 1 : 0, display: 'flex', gap: '10px'
      }}>
        <div style={{
          width: '40px', height: '40px', borderRadius: '50%',
          background: '#b6d36b', display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff', fontSize: '22px', boxShadow: '0 2px 8px #ecebe7', cursor: 'pointer'
        }} onClick={onPhoneClick}>
          <span role="img" aria-label="电话">📞</span>
        </div>
        <div style={{
          width: '40px', height: '40px', borderRadius: '50%',
          background: '#6ec1e4', display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff', fontSize: '22px', boxShadow: '0 2px 8px #ecebe7', cursor: 'pointer'
        }} onClick={onChatClick}>
          <span role="img" aria-label="聊天">💬</span>
        </div>
      </div>
      {/* 医生卡片本体 */}
      <div
        style={{
          background: '#fff', borderRadius: '16px', boxShadow: '0 1px 4px #ecebe7',
          display: 'flex', alignItems: 'center', padding: '12px 16px', transform: `translateX(${offset}px)`,
          transition: dragging.current ? 'none' : 'transform 0.2s'
        }}
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
      >
        <img src={avatar} alt="医生" style={{width:'48px',height:'48px',borderRadius:'50%',objectFit:'cover',marginRight:'12px'}} />
        <div style={{flex:1}}>
          <div style={{fontWeight:600,fontSize:'16px',color:'#4a3a2c',display:'flex',alignItems:'center',gap:'6px'}}>
            {name} {checked && <span style={{color:'#ff9800',fontSize:'18px'}}>✔</span>}
          </div>
          <div style={{fontSize:'15px',color:'#b0a99a',margin:'2px 0'}}>{tag} <span style={{margin:'0 4px'}}>·</span> <span role="img" aria-label="定位">📍</span> {meta}</div>
          <div style={{display:'flex',alignItems:'center',gap:'4px',marginTop:'2px'}}>
            <span style={{color:'#ffe066'}}>★★★☆☆</span>
            <span style={{color:'#b0a99a',fontSize:'15px'}}>{score}</span>
            <span style={{color:'#b0a99a',fontSize:'15px'}}>{users} 位用户</span>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function Home() {
  const navigate = useNavigate();

  
  // 呼吸动画：sin波平滑scale，周期约3秒
  const [breath, setBreath] = useState(1);
  // 弗洛伊德分数动态
  const [score, setScore] = useState(80);
  // 平滑动画分数
  const [displayScore, setDisplayScore] = useState(80);
  // 平滑动画percent
  const [displayPercent, setDisplayPercent] = useState(80);
  // 新增：点击状态 0-正常 1-高分区间
  const [scoreStage, setScoreStage] = useState(0);

  // 新增：卡片滑动与小圆点联动
  const metricsRef = useRef(null);
  const [currentIndex, setCurrentIndex] = useState(0);
  const cardCount = metrics.length;

  // 监听滚动，更新currentIndex
  useEffect(() => {
    const el = metricsRef.current;
    if (!el) return;
    function onScroll() {
      const cardWidth = el.firstChild ? el.firstChild.offsetWidth : 1;
      const idx = Math.round(el.scrollLeft / cardWidth);
      setCurrentIndex(idx);
    }
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, []);

  // 点击小圆点，滚动到对应卡片
  const handleDotClick = idx => {
    const el = metricsRef.current;
    if (!el) return;
    const cardWidth = el.firstChild ? el.firstChild.offsetWidth : 1;
    el.scrollTo({ left: cardWidth * idx, behavior: 'smooth' });
    setCurrentIndex(idx);
  };

  useEffect(() => {
    let t = 0;
    let running = true;
    function animate() {
      t += 0.04;
      setBreath(1 + 0.18 * (0.5 + 0.5 * Math.sin(t)));
      if (running) requestAnimationFrame(animate);
    }
    animate();
    return () => { running = false; };
  }, []);
  // 分数定时器，依赖scoreStage
  useEffect(() => {
    const timer = setInterval(() => {
      if (scoreStage === 1) {
        setScore(96 + Math.floor(Math.random() * 15)); // 96~110
      } else {
        setScore(75 + Math.floor(Math.random() * 12)); // 75~86
      }
    }, 3000);
    return () => clearInterval(timer);
  }, [scoreStage]);
  // 平滑动画分数
  useEffect(() => {
    let running = true;
    function animate() {
      setDisplayScore(s => Math.abs(s - score) < 0.2 ? score : s + (score - s) * 0.18);
      setDisplayPercent(p => Math.abs(p - score) < 0.2 ? score : p + (score - p) * 0.18);
      if (running) requestAnimationFrame(animate);
    }
    animate();
    return () => { running = false; };
  }, [score]);

  // 在Home组件内，计算speed
  const ecgSpeed = displayScore < 90 ? 0.004 : 0.01;

  // 点击事件：切换分数区间
  const handleFloydClick = () => {
    setScoreStage(s => (s + 1) % 2);
  };

  // 在Home组件内，定义情绪卡片的动态内容
  const emotionStages = [
    { icon: '😐', value: '平静', color: style.metricBlue }, // 平静
    { icon: '😰', value: '紧张', color: style.metricRed }, // 紧张
  ];

  return (
    <div className={style.homeContainer}>
      {/* 顶部栏 */}
      <header className={style.header}>
        <div className={style.headerTop}>
          <span className={style.date}><CalendarPotIcon /> {getTodayStr()}</span>
          <div className={style.bellWrap}>
            <BellIcon />
            <span className={style.bellDot}>7</span>
          </div>
        </div>
        <div className={style.profileSection}>
          <div className={style.avatar}></div>
          <div className={style.greetingBlock}>
            <div className={style.greeting}><span>嗨，</span><b>KOTO!</b></div>
            <div className={style.profileInfo}>
              <span className={style.profileItem}><span className={style.iconStar}>⭐</span> 专业版</span>
              <span className={style.dot}>·</span>
              <span className={style.profileItem}><span className={style.iconFlower}>🌼</span> 80%</span>
              <span className={style.dot}>·</span>
              <span className={style.profileItem}><span className={style.iconSmile}>😊</span> 快乐的</span>
            </div>
          </div>
        </div>
        <div className={style.searchBarWrap}>
          <div className={style.searchBarDark}>
            <input placeholder="输入关键词搜索…" />
            <span className={style.searchIcon}></span>
          </div>
        </div>
      </header>

      {/* 心理健康指标 */}
      <section className={style.section}>
        <h2 className={style.sectionTitle}>心理健康指标</h2>
        <div className={style.metricsRowScroll} ref={metricsRef}>
          {metrics.map((m, i) => {
            if (m.title === '情绪') {
              const stage = scoreStage % 2;
              return (
                <div className={style.metricCard + ' ' + emotionStages[stage].color} key={i}>
                  <div className={style.metricCardTop}>
                    <span className={style.metricIcon}>{emotionStages[stage].icon}</span>
                    <span className={style.metricTitle}>{m.title}</span>
                  </div>
                  <div className={style.metricEmotionText}>{emotionStages[stage].value}</div>
                  <div className={style.metricBarWrap}>
                    <BarChart values={m.bar} />
                  </div>
                </div>
              );
            }
            // 其他卡片保持原逻辑
            return (
              <div
                className={style.metricCard + ' ' + m.color}
                key={i}
                {...(m.title === '弗洛伊德评分' ? { onClick: handleFloydClick, style: { cursor: 'pointer' } } : {})}
              >
                <div className={style.metricCardTop}>
                  {/* 只在非弗洛伊德评分卡片顶部显示icon */}
                  {m.title !== '弗洛伊德评分' && <span className={style.metricIcon}>{m.icon}</span>}
                  <span className={style.metricTitle}>{m.title}</span>
                </div>
                {m.type === 'circle' && (
                  <div className={style.metricCircleRow}>
                    {/* 呼吸心脏+呼吸心电图 */}
                    {m.title === '弗洛伊德评分' && (
                      <div style={{display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',height:'90px'}}>
                        <GradientHeart breath={breath} />
                        <AnimatedECG amplitude={breath} speed={ecgSpeed} />
                      </div>
                    )}
                    <div className={style.metricCircleWrap}>
                      <CircleProgress percent={m.title === '弗洛伊德评分' ? displayPercent : m.percent} color="#fff" />
                      <div className={style.metricCircleText}>
                        <div className={style.metricValue}>{m.title === '弗洛伊德评分' ? Math.round(displayScore) : m.value}</div>
                        <div className={style.metricLabel}>{m.label}</div>
                      </div>
                    </div>
                  </div>
                )}
                {m.type === 'bar' && (
                  <>
                    <div className={style.metricEmotionText}>{m.value}</div>
                    <div className={style.metricBarWrap}>
                      <BarChart values={m.bar} />
                    </div>
                  </>
                )}
                {m.type === 'number' && (
                  <div className={style.metricNumberWrap}>
                    <div className={style.metricValue}>{m.value}</div>
                    <div className={style.metricLabel}>{m.label}</div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
        <div className={style.metricsDots}>
          {metrics.map((_, i) => (
            <span
              key={i}
              className={style.metricsDot + (i === currentIndex ? ' ' + style.metricsDotActive : '')}
              onClick={() => handleDotClick(i)}
              style={{ cursor: 'pointer' }}
            ></span>
          ))}
        </div>
      </section>

      {/* 正念追踪器 */}
      <section className={style.section}>
        <h2 className={style.sectionTitle}>正念追踪器</h2>
        <div className={style.trackerList}>
          <div className={style.trackerCard}>
            <div style={{display:'flex',alignItems:'center'}}>
              <div className={style.trackerIcon + ' ' + style.trackerGreen}>📞</div>
              <div>
                <div className={style.trackerTitle}>正念时间</div>
                <div className={style.trackerDesc}>今日 2.5 小时/8 小时</div>
              </div>
            </div>
            <div style={{fontSize:'28px',color:'#6db36d'}}>~</div>
          </div>
          <div className={style.trackerCard}>
            <div style={{display:'flex',alignItems:'center'}}>
              <div className={style.trackerIcon + ' ' + style.trackerPurple}>😴</div>
              <div>
                <div className={style.trackerTitle}>睡眠质量</div>
                <div className={style.trackerDesc}>失眠症（平均约2小时）</div>
              </div>
            </div>
            <div style={{width:'38px',height:'38px',borderRadius:'50%',background:'#f3f0fa',display:'flex',alignItems:'center',justifyContent:'center',fontSize:'15px',color:'#a48eea'}}>5级</div>
          </div>
          <div className={style.trackerCard}>
            <div style={{display:'flex',alignItems:'center'}}>
              <div className={style.trackerIcon + ' ' + style.trackerOrange}>📝</div>
              <div>
                <div className={style.trackerTitle}>正念日记</div>
                <div className={style.trackerDesc}>连续 64 天</div>
              </div>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'repeat(4,8px)',gap:'3px',marginRight:'2px'}}>
              {Array.from({length:12}).map((_,i)=>(<div key={i} style={{width:'8px',height:'8px',borderRadius:'2px',background:i<8?'#ff9800':'#f6cfa1',opacity:i<8?1:0.4}}></div>))}
            </div>
          </div>
          <div className={style.trackerCard}>
            <div style={{display:'flex',alignItems:'center'}}>
              <div className={style.trackerIcon + ' ' + style.trackerYellow}>💡</div>
              <div>
                <div className={style.trackerTitle}>压力水平</div>
                <div className={style.trackerDesc}>3级（普通）</div>
              </div>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:'2px'}}>
              {Array.from({length:5}).map((_,i)=>(<div key={i} style={{width:'18px',height:'6px',borderRadius:'3px',background:i<3?'#ffe066':'#f3eac2',opacity:1}}></div>))}
            </div>
          </div>
        </div>
       
      </section>
   {/* 心理健康症状 */}
   <section className={style.section}>
        <div className={style.sectionHeader}>
          <h2 className={style.sectionTitle}>心理健康症状</h2>
          <a className={style.sectionLink}>查看全部</a>
        </div>
        <div className={style.symptomCard}>
          <div className={style.symptomCount}>16 症状</div>
          <input className={style.symptomSearch} placeholder="搜索精神症状.." />
          我的症状：
          <div className={style.symptomTags}>
         
            <span>头晕</span>
            <span>压力</span>
            <span>焦虑</span>
          </div>
        </div>
      </section>
      {/* 预约医生 */}
      <section className={style.appointCard}>
        <div className={style.appointHeader}>
          医生
          <a className={style.appointAll}
          onClick={()=>{
            navigate('/Layout');
          }}
          >查看全部</a>
        </div>
        <div className={style.appointMainRow}>
          <div>
            <span className={style.appointNum}>87</span>
            <span className={style.appointNumLabel}>推荐</span>
          </div>
       
        </div>
        <div className={style.appointStatusRow}>
          <span className={style.appointStatus + ' ' + style.green}><span className="icon">🟢</span>2 即将进行</span>
          <span className={style.appointStatus + ' ' + style.red}><span className="icon">❌</span>4 取消</span>
          <span className={style.appointStatus + ' ' + style.gray}><span className="icon">🔄</span>1 重新安排</span>
        </div>
        <div className={style.appointList}>
          <div style={{margin:'18px 0 0 0'}}>
            <SwipeDoctorCard avatar="../public/ljx/6.jpg" name="医生昵称" tag="压力" score="4.1" users="96" checked onPhoneClick={() => navigate('/list')} onChatClick={() => navigate('/login')} />
            <SwipeDoctorCard avatar="../public/ljx/13.jpg" name="医生昵称" tag="强迫症专家" score="3.4" users="221" onPhoneClick={() => navigate('/list')} onChatClick={() => navigate('/login')} />
          </div>
        </div>
        <a className={style.appointAllLink}>查看所有预约</a>
      </section>

   

     

      {/* AI聊天机器人 */}
      <section className={style.section}>
        <h2 className={style.sectionTitle}>人工智能治疗聊天机器人</h2>
        <div className={style.aiBotCard}>
          <div className={style.aiBotInfo}>
            <div className={style.aiBotCount}>2,541 对话</div>
            <div className={style.aiBotDesc}>本月还剩 83 人</div>
          </div>
          <div className={style.aiBotImage}></div>
        </div>
      </section>
    </div>
  );
}